package com.shop.utils;


import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import lombok.Data;

@Component
@Data
public class JWTUtils {
    @Value("${jwt.signingKey}")  
    private String signingKey;  
    @Value("${jwt.expireTimeMinutes}")  
    private Integer expireTimeMinutes; 
    public String getToken(String userId, String userName) {

        Calendar instance = Calendar.getInstance();
        // 单位分钟
        instance.add(Calendar.MINUTE, expireTimeMinutes);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        // payload
        Map<String, String> payload = new HashMap<>();
        payload.put("id",userId);
        payload.put("name",userName);
        payload.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        String token = builder.withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256(signingKey));  // sign
        return token;
    }
    /**
     * 验证token  合法性
     */
    public DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(signingKey)).build().verify(token);
    }

}
